package tp1rmi;

import exceptions.AnnuiteApplicationException;
import exceptions.CalculAnnuiteApplicationException;
import exceptions.MontantApplicationException;
import exceptions.NbAnneesApplicationException;
import exceptions.TauxApplicationException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class RemotePretImpl extends UnicastRemoteObject implements RemotePret {

    public RemotePretImpl() throws RemoteException {
        super();
    }

    @Override
    public Double getAnnuite(Double montant, int nb_annees, Double taux) throws RemoteException, AnnuiteApplicationException, MontantApplicationException, TauxApplicationException, NbAnneesApplicationException {
        if (this.verifMontant(montant)) {
            throw new MontantApplicationException();
        }
        if (this.verifNbAnnees(nb_annees)) {
            throw new NbAnneesApplicationException();
        }
        if (this.verifTaux(taux)) {
            throw new TauxApplicationException();
        }
        taux = taux / 100;
        return montant * (taux / (1 - Math.pow(1 + taux, -nb_annees)));
    }

    @Override
    public Double getNbAnnees(int annuites, Double montant, Double taux) throws RemoteException, AnnuiteApplicationException, MontantApplicationException, TauxApplicationException, NbAnneesApplicationException, CalculAnnuiteApplicationException {
        if (this.verifMontant(montant)) {
            throw new MontantApplicationException();
        }
        if (this.verifAnnuite(annuites)) {
            throw new AnnuiteApplicationException();
        }
        if (this.verifTaux(taux)) {
            throw new TauxApplicationException();
        }

        taux = taux / 100;

        if (taux * montant > annuites) {
            throw new CalculAnnuiteApplicationException();
        }

        return -Math.log(1 - (taux * montant) / annuites) / Math.log(1 + taux);
    }

    private boolean verifMontant(Double pMontant) {
        if (pMontant <= 0) {
            return true;
        }
        return false;
    }

    private boolean verifTaux(Double pTaux) {
        if (pTaux <= 0) {
            return true;
        }
        return false;
    }

    private boolean verifAnnuite(int pAnnuite) {
        if (pAnnuite <= 0) {
            return true;
        }
        return false;
    }

    private boolean verifNbAnnees(int pNbAnnees) {
        if (pNbAnnees <= 0) {
            return true;
        }
        return false;
    }
}